// 路由工具函数

/**
 * 检查路由是否需要权限验证
 * @param {Object} route - 路由对象
 * @returns {Boolean}
 */
export function requiresAuth(route) {
  return route.meta?.requiresAuth !== false
}

/**
 * 生成面包屑导航
 * @param {Object} route - 当前路由
 * @param {Array} menus - 菜单数据
 * @returns {Array}
 */
export function generateBreadcrumb(route, menus) {
  const breadcrumb = []
  const pathArray = route.path.split('/').filter(Boolean)
  
  let currentPath = ''
  pathArray.forEach(path => {
    currentPath += `/${path}`
    const menu = findMenuByPath(currentPath, menus)
    if (menu) {
      breadcrumb.push({
        title: menu.menuName,
        path: menu.path
      })
    }
  })
  
  return breadcrumb
}

/**
 * 根据路径查找菜单
 * @param {String} path - 路径
 * @param {Array} menus - 菜单数据
 * @returns {Object|null}
 */
export function findMenuByPath(path, menus) {
  for (const menu of menus) {
    if (menu.path === path) {
      return menu
    }
    if (menu.children && menu.children.length > 0) {
      const found = findMenuByPath(path, menu.children)
      if (found) {
        return found
      }
    }
  }
  return null
}

/**
 * 检查菜单是否可见
 * @param {Object} menu - 菜单对象
 * @returns {Boolean}
 */
export function isMenuVisible(menu) {
  return menu.visible === 1 && !menu.hidden
}

/**
 * 过滤并处理菜单数据
 * @param {Array} menus - 原始菜单数据
 * @returns {Array}
 */
export function processMenus(menus) {
  return menus
    .filter(menu => isMenuVisible(menu))
    .map(menu => {
      const processedMenu = { ...menu }
      if (menu.children && menu.children.length > 0) {
        processedMenu.children = processMenus(menu.children)
      }
      return processedMenu
    })
}

/**
 * 获取默认激活的菜单路径
 * @param {String} currentPath - 当前路径
 * @param {Array} menus - 菜单数据
 * @returns {String}
 */
export function getActiveMenuPath(currentPath, menus) {
  // 精确匹配
  if (findMenuByPath(currentPath, menus)) {
    return currentPath
  }
  
  // 模糊匹配，查找最长匹配的路径
  let bestMatch = ''
  const findBestMatch = (menus) => {
    menus.forEach(menu => {
      if (currentPath.startsWith(menu.path) && menu.path.length > bestMatch.length) {
        bestMatch = menu.path
      }
      if (menu.children && menu.children.length > 0) {
        findBestMatch(menu.children)
      }
    })
  }
  
  findBestMatch(menus)
  return bestMatch || currentPath
}